/**
 * @author FengLei.You
 */
function TiledLayer(opt){
	Me.extend(Layer,TiledLayer);
	TiledLayer.parent.constructor.call(this,opt);
	
	this.rows=opt.rows;
	this.columns=opt.columns;
	
	this.image=opt.image;
	this.tileWidth=opt.tileWidth;
	this.tileHeight=opt.tileHeight;
	
	//可以支持缩放?
	this.cellWidth=this.tileWidth;
	this.cellHeight=this.tileHeight;	
	
	this._cells=opt._cells||[];
	this._animateMap=opt._animateMap||{};
}
TiledLayer.prototype.fillCells=function(row,column,numRow,numCol,tileIndex){
	for(var i=row;i<numRow;i++){
		for(var j=column;j<numCol;j++){
			this._cells[i][j]=tileIndex;
		}
	}
}
//mapeditor generate data
//need edit the imagesrc to right with resourcemanager
TiledLayer.prototype.setMapObject=function(obj){
	if(obj && obj.mapData){
		this.rows=obj.rowSize;
		this.columns=obj.columnSize;
		
		this.image=Me.resourceManager.getImage(obj.imageSrc);
		this.cellWidth=this.tileWidth=obj.unitWidth;
		this.cellHeight=this.tileHeight=obj.unitHeight;
		
		this._cells=obj.mapData;		
	}
}
/**
 * 当一个块,可能变换成多个不同块的时候.
 * 这个块的index应该为  负值. 从-1开始
 *
 * 
 * 本方法 设置 负值索引 在下一个绘制轮回中将要绘制的 图片索引
 * 如 -1=>2
 */
TiledLayer.prototype.setAnimatedTile=function(animatedIndex,staticTileIndex){
	this._animateMap[animatedIndex]=staticTileIndex;
}
TiledLayer.prototype.getAnimatedTile=function(animatedTileIndex){
	return this._animateMap[animatedIndex];
}
TiledLayer.prototype.setCell=function(row,col,tileIndex){
	this._cells[row][col]=tileIndex;
}
TiledLayer.prototype.getCell=function(row,col){
	return this._cells[row][col];
}
TiledLayer.prototype.getCellWidth=function(){
	return this.cellWidth;
}
TiledLayer.prototype.getCellHeight=function(){
	return this.cellHeight;
}
TiledLayer.prototype.getRows=function(){
	return this.rows;
}
TiledLayer.prototype.getColumns=function(){
	return this.columns;
}

TiledLayer.prototype.setStaticTileSet=function(image,tileWidth,tileHeight){
	this.image=image;
	this.tileWidth=tileWidth;
	this.tileHeight=tileHeight;
}
TiledLayer.prototype.paint=function(context){
	//context.drawImage(imageObj, sourceX, sourceY, sourceWidth,
	//	sourceHeight, destX, destY, destWidth, destHeight);
	context.clearRect(this.top,this.left,this.width,this.height);
	
	for(var row=0;row<this.rows;row++){
		for(var column=0;column<this.columns;column++){
			var staticImageIndex=this._cells[row][column];
			
			if(staticImageIndex>0){
				
				var srcImageColumns = this.image.width/this.tileWidth;			
				var srcImageLeft = parseInt(staticImageIndex%srcImageColumns);
				var srcImageTop = parseInt(staticImageIndex/srcImageColumns);
				
				context.drawImage(this.image,
					srcImageLeft*this.tileWidth,srcImageTop*this.tileHeight,this.tileWidth,this.tileHeight,
					column*this.cellWidth,row*this.cellHeight,this.cellWidth,this.cellHeight);
			}						
		}
	}	
}



































